<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询文件夹名称" v-model="searchFolderName"></el-input>
      <el-button type="primary" @click="loadFolders(1)">查询</el-button>
      <el-button type="info" @click="resetSearch">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增文件夹</el-button>
    </div>
    <el-table :data="foldersData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }">
      <el-table-column prop="folderid" label="文件夹ID" width="70" align="center"></el-table-column>
      <el-table-column prop="foldername" label="文件夹名称"></el-table-column>
      <el-table-column prop="classid" label="班级ID"></el-table-column>
      <el-table-column prop="creatorid" label="创建者ID"></el-table-column>
      <el-table-column prop="name" label="创建者姓名"></el-table-column>
      <el-table-column prop="creationdate" label="创建日期"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="del(scope.row.folderid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="文件夹信息" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="文件夹名称" prop="foldername">
          <el-input v-model="form.foldername" placeholder="文件夹名称"></el-input>
        </el-form-item>
        <el-form-item label="班级ID" prop="classid">
          <el-input v-model="form.classid" placeholder="班级ID"></el-input>
        </el-form-item>
        <el-form-item label="创建者ID" prop="creatorid">
          <el-input v-model="form.creatorid" placeholder="创建者ID"></el-input>
        </el-form-item>
        <el-form-item label="创建日期" prop="creationdate">
          <el-date-picker v-model="form.creationdate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Folders",
  data() {
    return {
      foldersData: [],  // 所有的文件夹数据
      pageNum: 1,       // 当前的页码
      pageSize: 10,     // 每页显示的个数
      searchFolderName: '',
      total: 0,
      dialogVisible: false,
      form: {},
      selectedIds: [],
      rules: {
        foldername: [
          { required: true, message: '请输入文件夹名称', trigger: 'blur' },
          { min: 1, max: 50, message: '文件夹名称长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        classid: [
          { required: true, message: '请输入班级ID', trigger: 'blur' }
        ],
        creatorid: [
          { required: true, message: '请输入创建者ID', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.loadFolders();
  },
  methods: {


        // 获取上传者名字
    //TODO: 待优化
    async fetchName(Id) {
      try {
        const res = await this.$request.get(`/users/selectNameById/${Id}`);
        console.log('获取上传者名字', res.data); 
        return res.data;
      } catch (error) {
        console.error('获取上传者名字失败', error);
        return null;
      }
    },

    delBatch() {
      // ... 批量删除方法 ...
    },
    handleSelectionChange(rows) {
      this.selectedIds = rows.map(v => v.folderid);
    },
    del(folderid) {
      // ... 删除方法 ...
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝
      this.dialogVisible = true;
    },
    handleAdd() {
      this.form = {}; // 清空表单
      this.dialogVisible = true;
    },
    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const url = this.form.folderid ? '/folders/update' : '/folders/add';
          const method = this.form.folderid ? 'PUT' : 'POST';
          this.$request({
            url: url,
            method: method,
            data: this.form
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('操作成功');
              this.dialogVisible = false;
              this.loadFolders(1);
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    resetSearch() {
      this.searchFolderName = '';
      this.loadFolders();
    },
    handleCurrentChange(pageNum) {
      this.loadFolders(pageNum);
    },
    
    async loadFolders(pageNum) {
      if (pageNum) this.pageNum = pageNum;
      try {
        const res = await this.$request.get('/folders/selectByPage', {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            folderName: this.searchFolderName
          }
        });


        this.foldersData = res.data.records || [];
        this.total = res.data.total || 0;
        //
        // 获取创建者名字
        for (let i = 0; i < this.foldersData.length; i++) {
          const folderid = this.foldersData[i].creatorid;
          const name = await this.fetchName(folderid);
          this.$set(this.foldersData[i], 'name', name);

        }


      } catch (error) {
        console.error('请求文件夹数据失败', error);
        this.foldersData = [];
        this.total = 0;
        this.$message.error('加载文件夹数据失败');
      }
    },
  },
};
</script>

<style scoped>

</style>